import axios from 'axios'
import md5 from 'js-md5';
import { showFailToast } from 'vant';
// create an axios instance
function formDataSign(formData){
  var query = JSON.parse(JSON.stringify(formData))
  const keys = []
  let sysStr = ''
  for (const key in query) {
    keys.push(key)
  }
  keys.sort().forEach(function (key) {
    var s = ''
    if (query[key] instanceof Array) {
      query[key].forEach((item, index) => {
        for (const ai in item) {
          if (item[ai] === null) {
            delete query[key][index][ai]
          }
        }
      })
      s = key + JSON.stringify(query[key])
    } else if (query[key] !== null) {
      s = key + query[key]
    }
    sysStr += s
  })
  var sig = md5(sysStr);
  return sig;
}
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 10 // request timeout
})
// request interceptor
service.interceptors.request.use(
  
  config => {
    if(config.data)config.headers['sig'] = formDataSign(config.data)
    if(config.params)config.headers['sig'] = formDataSign(config.params)
    
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (!res.success) {
      Promise.reject(new Error(res.respMsg || 'Error'))
      return res
    } else {
      return res
    }
  },
  error => {
    const err = error.response
    showFailToast(err.data.respMsg)
    console.error("err---------",err) // for debug
    return Promise.reject(error)
  }
)

export default service
